<?php

session_start();

// include settings and functions
include "../conn/database.php";
include "functions.php";
include 'UUID.php';

// if the user submit the form
if(isset($_POST['submit'])) {
	// initialize errors values
	$errors=0;
	$errors_text = '';
	// cleanning the post data from hacking attempt
	$post_data = clean($_POST);
	
	// get the number of questions
	$numOfQuestion = 0;
	for($i = 1; $i<100; $i++){
		if(!isset($post_data['Question'.$i])){
		break;
		}
		$numOfQuestion = $i;
	}
	
	// empty post data verification
	for($i = 1; $i <= $numOfQuestion; $i++){
		if(empty($post_data['Question'.$i]) || empty($post_data['A'.$i])) {
			$errors_text .= "Des champs sont vides";
			$errors++;
		}
	}
	if(empty($post_data['addhistoire-step'])) {
		$errors_text .= "error addhistoire-step<br />";
		$errors++;
	}
	
	// if no errors we proceed
	if($errors == 0) {	
		
		// generating the INTERVIEW ID
		$inid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', generate_guid(6));
		//read wedding ID
		$wid = $_SESSION['wid'];
		
		if($post_data['addhistoire-step'] == 'step-1'){
			$tagTable = "INTERVIEW_ID_LEFT";
			$tagURL = "histoire.php?step=2";
			$_SESSION['linid'] = $inid;
		} else if($post_data['addhistoire-step'] == 'step-2') {
			$tagTable = "INTERVIEW_ID_RIGHT";
			$tagURL = "histoire.php?step=3";
			$_SESSION['rinid'] = $inid;
		} else if($post_data['addhistoire-step'] == 'step-3') {
			$tagTable = "INTERVIEW_ID_BOTH";
			$tagURL = "grandjour.php?event=1";
			$_SESSION['binid'] = $inid;
		} else {
			$errors_text .= "error addhistoire-step<br />";
			$errors++;
		}
		
		$updateWedding = mysql_query("UPDATE `T_WEDDINGS`  
																	SET ".$tagTable." ='".$inid."'
																	WHERE WEDDING_ID = '".$wid."'");
		$insertInterview = mysql_query("INSERT INTO `T_INTERVIEWS`
																			(INTERVIEW_SID)
																		VALUES
																			('".$inid."')");

		for($i = 1; $i <= $numOfQuestion; $i++){
			$qid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', generate_guid(6));
			$insert_sql = "
				INSERT INTO `T_ESPOUSER_QUESTIONS_ANSWERS` 
					(`INTERVIEW_SID`, `QUESTION_ID`, `QUESTION_FR`, `ANSWER_FR`, `INDEX`)
				VALUES
					('".$inid."','".$qid."','".$post_data['Question'.$i]."','".$post_data['A'.$i]."','".$i."')"
			;
			
			if(!mysql_query($insert_sql)) {
					$errors_text .= mysql_error()."<br />";
					$errors++;
			}
		}
	}
	if($errors == 0) {
		$arr['success'] = "1"; 
        $arr['msg'] = 'Vos informations ont bien été enregistrées.';
		$arr['url'] = $tagURL;
	} else {
		$arr['success'] = "0"; 
        $arr['msg'] = $errors_text;
	}
	echo json_encode($arr);
}
?>